package com.sfac.springBoot.modules.test.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sfac.springBoot.modules.common.vo.Result;
import com.sfac.springBoot.modules.common.vo.Search;
import com.sfac.springBoot.modules.test.dao.CityDao;
import com.sfac.springBoot.modules.test.entity.City;
import com.sfac.springBoot.modules.test.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class CityServiceImpl implements CityService {
    @Autowired
    private CityDao cityDao;
    @Override
    @Transactional
    public Result<City> insert(City city) {
        City city1 = cityDao.selectCityByName(city.getCityName());
        if (city1!=null){
            return new Result<>(Result.ResultStatus.ERROR.code,"城市名重复");
        }
        city.setDateCreated(LocalDateTime.now());
        city.setDateModified(LocalDateTime.now());
         cityDao.insertCity(city);
        return new Result<>(Result.ResultStatus.SUCCESS.code,"插入成功",city);
    }

    @Override
    @Transactional
    public Result<City> update(City city) {
        City city1 = cityDao.selectCityByName(city.getCityName());
        if (city1!=null&&city1.getCityId()!=city.getCityId()){
            return new Result<>(Result.ResultStatus.ERROR.code,"城市名重复");
        }
        city.setDateModified(LocalDateTime.now());
        cityDao.updateCity(city);
        return new Result<>(Result.ResultStatus.SUCCESS.code,"修改成功",city);
    }

    @Override
    public Result<Object> delete(int cityId) {
        cityDao.deleteCity(cityId);
        return new Result<>(Result.ResultStatus.SUCCESS.code,"删除成功");
    }

    @Override
    public City queryById1(int cityId) {
        return cityDao.queryById1(cityId);
    }
    @Override
    public List<City> queryById2(int countyId) {
        return cityDao.queryById2(countyId);
    }

    @Override
    public PageInfo<City> queryById3(Search search) {
        search.init();
        PageHelper.startPage(search.getCurrentPage(),search.getPageSize());
        return new PageInfo<City>(Optional.ofNullable(cityDao.getCitiesBySearch(search)).orElse(Collections.emptyList()));
    }
}
